﻿using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using static UnityEngine.UI.CanvasScaler;

public class ActionQueuePanel : MonoBehaviour
{
    public HorizontalLayoutGroup HorizontalSettings;
    public RectTransform ContentRectTrans;
    public GameObject ActionQueueUnitPrefab;
    public float ImageSize = 290f;

    Team Viewer;

    List<ActionQueueUnitImage> ActionQueueUnits = new List<ActionQueueUnitImage>();
    private void Start()
    {
        MessageManager.Instance.AddListener(ClientEvent.Refresh, Refresh);
        MessageManager<UnitBase>.Instance.AddListener(ClientEvent.UnitEnd, RemoveUnit);
    }
    private void OnDestroy()
    {
        MessageManager.Instance.RemoveListener(ClientEvent.Refresh, Refresh);
        MessageManager<UnitBase>.Instance.RemoveListener(ClientEvent.UnitEnd, RemoveUnit);
    }
    public void SetActionQueueDisplay(List<UnitBase> units, Team viewer)
    {
        Viewer = viewer;
        for (int i = 0; i < ActionQueueUnits.Count; i++)
        {
            Destroy(ActionQueueUnits[i].gameObject);
        }
        ActionQueueUnits.Clear();
        float contentLen = ImageSize * units.Count +
            HorizontalSettings.padding.left + HorizontalSettings.padding.right +
            HorizontalSettings.spacing * (units.Count - 1);
        //Debug.Log(contentLen);
        ContentRectTrans.SetSizeWithCurrentAnchors(RectTransform.Axis.Horizontal, contentLen);

        for (int i = 0; i < units.Count; i++)
        {
            GameObject unitGoInstance = GameObject.Instantiate(ActionQueueUnitPrefab, ContentRectTrans);
            ActionQueueUnitImage actionQueueUnitImage = unitGoInstance.GetComponent<ActionQueueUnitImage>();
            actionQueueUnitImage.SetUnit(units[i], Viewer);
            actionQueueUnitImage.RefreshSprite();
        }
    }

    public void Refresh()
    {
        for (int i = 0; i < ActionQueueUnits.Count; i++)
        {
            ActionQueueUnits[i].RefreshSprite();
        }
    }

    public void RemoveUnit(UnitBase unit)
    {
        for (int i = 0;i < ActionQueueUnits.Count;i++)
        {
            if (ActionQueueUnits[i].Unit == unit)
            {
                RemoveUnit(i);
                break;
            }
        }
    }

    public void RemoveUnit(int index)
    {
        ActionQueueUnits[index].DestroySelf();
        ActionQueueUnits.RemoveAt(index);
    }
}